<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * Configuration class
 */
class Config {
	const DEFAULT_PART = 'default';

	private static $_instance = null;
	private $_container = array();

	public static function &instance() {
		if (!isset(self::$_instance)) {
			$c = __CLASS__;
			self::$_instance = new $c;
		}

		return self::$_instance;
    }

	private function __construct() {}

	public function __clone() {
		throw new Node_Exception('Can`t clone singletone object');
	}

	/**
	 * Loading config file
	 */
	public static function load($part = self::DEFAULT_PART) {
		$part = self::_fixPart($part);
		$config = self::instance();

		if (!isset($config->_container[$part])) {
			$file = strtolower($part);
			$paths = Node::findFile('config', $file);
			if (!empty($paths)) {
				foreach ($paths as $path) {
					$arr = include($path);
					$config->setArray($arr, $part);
				}
			}
		}
		return $config;
	}

	/**
	 * Return config value
	 */
	public static function get($offset, $part = self::DEFAULT_PART, $default = '') {
		$result = $default;

		$part = self::_fixPart($part);
		self::load($part);

		$config = self::instance();
		if (isset($config->_container[$part])) {		
			$result = Arr::get($config->_container[$part], $offset, $default);
		}

		return $result;
	}

	/**
	 * Storing config value
	 */
	public static function set($offset, $value, $part = self::DEFAULT_PART) {
		$part = self::_fixPart($part);
		$config = self::instance();

		if (!isset($config->_container[$part])) {
			$config->_container[$part] = array();
		}
		
		$config->_container[$part][$offset] = $value;
	}

	/**
	 * Storing config array
	 */
	public static function setArray($array, $part = self::DEFAULT_PART) {
		$part = self::_fixPart($part);
		$config = self::instance();

		if (!isset($config->_container[$part])) {
			$config->_container[$part] = array();
		}
		$config->_container[$part] = array_merge($config->_container[$part], $array);
	}

	/**
	 * Output all config values
	 */
	public static function dump() {
		$config = self::instance();
		echo '<pre>', print_r($config->_container, true), '</pre>';
	}

	private static function _fixPart($part = self::DEFAULT_PART) {
		if (empty($part)) {
			$part = self::DEFAULT_PART;
		}

		return trim(strtolower($part));
	}
}